//
//  RegisterViewController.swift
//  weile
//
//  Created by LKM on 16/10/8.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit
import Foundation
//丫的 修改密码 直接写这里了
class RegisterViewController: BaseViewController {

    var isFindPassPage :Bool = false {
        didSet {
            if(isFindPassPage){
                lbl_tips_reg.isHidden=true;
                btn_submint.setText("修改密码")
            }
        }
        
        
    }
    
    @IBOutlet weak var lbl_tips_reg: UILabel!
    @IBOutlet weak var btn_code: UIButton!

    @IBOutlet weak var btn_submint: BtnBase!
    @IBOutlet weak var tx_phone: UITextField!
    @IBOutlet weak var tx_pass: UITextField!
    @IBOutlet weak var tx_code: UITextField!
    
    @IBOutlet weak var tx_phone_leftView: UIImageView!
    @IBOutlet weak var tx_pass_leftView: UIImageView!
    @IBOutlet weak var tx_code_leftView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        btn_submint.backgroundColor = R.colors.blue
        
        ViewHelp.setPadding(btn_code, pa:8)
        
        ViewHelp.setHtmlText(lbl_tips_reg,"<font color='#fff'><u>点击注册表示同意用户协议</u></font>");
        
        ViewHelp.setOnClickListening(lbl_tips_reg, self, #selector(onRegProtocolClick) )
        
        tx_phone.borderStyle =  UITextBorderStyle.none;
        tx_phone.keyboardType = UIKeyboardType.phonePad;
        
        tx_pass.isSecureTextEntry=true;
        
        tx_code.keyboardType = UIKeyboardType.numberPad;
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
        tx_phone_leftView.removeFromSuperview();
        tx_phone.leftView = tx_phone_leftView;
        tx_phone.leftViewMode = UITextFieldViewMode.always
        //        tx_phone.leftView!.x += 15;
        
        tx_pass_leftView.removeFromSuperview();
        tx_pass.leftView = tx_pass_leftView
        tx_pass.leftViewMode = UITextFieldViewMode.always
        
        tx_code_leftView.removeFromSuperview();
        tx_code.leftView = tx_code_leftView
        tx_code.leftViewMode = UITextFieldViewMode.always
    }
    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }
    
    //------keyboard 键盘不挡住输入框---copy http://blog.apoorvmote.com/move-uitextfield-up-when-keyboard-appears/ ----
    override func viewWillDisappear(_ animated: Bool) {
        countDownTimer?.invalidate()
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func keyboardWillShow(notification:NSNotification) {
        adjustingHeight(show: true, notification: notification)
    }
    
    func keyboardWillHide(notification:NSNotification) {
        adjustingHeight(show: false, notification: notification)
    }
    
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    func adjustingHeight(show:Bool, notification:NSNotification) {
        //        ViewHelp.showTipsView(containView: view, tips: "ccc")
        // 1
        var userInfo = notification.userInfo!
        // 2
        let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        // 3
        let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        // 4
        var changeInHeight = (keyboardFrame.height-140) ;//100随意调整
        if(!show){
            changeInHeight=0;
        }
        //5
        UIView.animate(withDuration: animationDurarion, animations: { () -> Void in
            //            self.bottomConstraint.constant += (keyboardFrame.height + 40) * (show ? 1 : -1)
            self.view.bounds = CGRect(x:0.0, y:changeInHeight,width:self.view.frame.size.width,height:self.view.frame.size.height);
        })
        
    }
    //------keyboard 键盘不挡住输入框--end-----

    
    @IBAction func onSendCodeClick(_ sender: AnyObject) {
       
        if ViewHelp.isTextEmpty(tx_phone) {
            ViewHelp.showTipsView(containView: self.view, tips: "请填写手机号");
            return;
        }
        
        if(btn_code.isEnabled){
            onSendCodeRequest();
            
        }
        
    }
    
    func onSendCodeRequest(){
        ViewHelp.showProgressActivity(containView: self.view);
        if(isFindPassPage){
            //开始计时，发送验证码
            let ts = Api.sendSmsAuthForFindPass(telephone: tx_phone.text!, end: { (re:ResponEntity) in
                ViewHelp.hideProgressActivity(containView: self.view);
                if(re.isSuccess()){
                    self.startCountDownTimer()
                }
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)
            })
            taskAlls.append(ts);
        }else{
            //开始计时，发送验证码
            let ts = Api.sendSmsAuthForReg(telephone: tx_phone.text!, end: { (re:ResponEntity) in
                ViewHelp.hideProgressActivity(containView: self.view);
                if(re.isSuccess()){
                    self.startCountDownTimer()
                }
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)
            })
            taskAlls.append(ts);
        }
    }
    
    @IBAction func onRegClick(_ sender: AnyObject) {
        if ViewHelp.isTextEmpty(tx_phone) {
            ViewHelp.showTipsView(containView: self.view, tips: "请填写手机号");
            return;
        }
        if ViewHelp.isTextEmpty(tx_pass) {
            ViewHelp.showTipsView(containView: self.view, tips: "请填写密码");
            return;
        }
        if ViewHelp.isTextEmpty(tx_code) {
            ViewHelp.showTipsView(containView: self.view, tips: "请填写验证码");
            return;
        }
        
        onSubmitRequest()
    }
    func onSubmitRequest(){
        if(isFindPassPage){
            //修改密码
            let ts=Api.PassAlter(telephone: tx_phone.text!, password: tx_pass.text!, mobile_valicode: tx_code.text!) { (re:ResponEntity) in
                if(re.isSuccess()){
                    ViewHelp.showAlertTipsDialog(tips: "密码修改成功！", okRun: { 
                        self.finish()
                    })
                }else{
                    ViewHelp.showTipsView(containView: self.view, tips: re.msg);
                }
            }
            taskAlls.append(ts);
        }else{
            let ts=Api.reg(telephone: tx_phone.text!, password: tx_pass.text!, mobile_valicode: tx_code.text!) { (re:ResponEntity) in
                if(re.isSuccess()){
                    ActivityRequest.goMain();
                }
                ViewHelp.showTipsView(containView: self.view, tips: re.msg);
                
            }
            taskAlls.append(ts);
        }
    }
    
    
    func onRegProtocolClick(){
//        ViewHelp.showTipsView(containView: self.view, tips: "hehds")
        ActivityRequest.goUserProtocolViewController(self.navigationController!);
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    var secondsCountDown = 60;//60秒倒计时
    var countDownTimer:Timer?;
    func startCountDownTimer(){
        btn_code.isEnabled=false;
        if countDownTimer != nil {
            return;
        }
        countDownTimer=Timer(timeInterval: 1, target: self, selector: #selector( countDownTimerDidFinish(_:)), userInfo: nil, repeats: true)
        RunLoop.main.add(countDownTimer!, forMode: RunLoopMode.commonModes)
    }
    func countDownTimerDidFinish(_ timer: Timer) {
        secondsCountDown -= 1;
        if(secondsCountDown==0){
            countDownTimer?.invalidate()
            countDownTimer = nil;
            secondsCountDown=60;
            btn_code.isEnabled = true;
            btn_code.setTitle("发送验证码", for: UIControlState.normal);
        }else{
            btn_code.isEnabled = false;
            
            UIView.performWithoutAnimation {
                    btn_code.setTitle("(\(secondsCountDown))s", for: UIControlState.normal);
            }
            
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
